package 栈;

import java.util.Scanner;

public class 链表模拟栈 {
	public static void main(String[] args) {
		// 创建栈
		LinkList stack = new LinkList();
		String key = "";
		boolean loop = true;
		Scanner scanner = new Scanner(System.in);
		while (loop) {
			System.out.println("s 查看栈");
			System.out.println("push 入栈");
			System.out.println("pop 出栈");
			System.out.println("e 退出");
			key = scanner.next();
			switch (key) {
			case "s":
				stack.showStack();
				break;
			case "push":
				System.out.println("入栈数据:");
				int data = scanner.nextInt();
				stack.push(new LinkNode(data));
				break;
			case "pop":
				try {
					LinkNode d = stack.pop();
					System.out.println(d);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case "e":
				loop = false;
				break;
			default:
				break;
			}
		}
	}

}

class LinkList {
	private LinkNode L;

	public LinkList() {
		L = new LinkNode();
		L.next = null;
	}

	// 栈空
	public boolean isEmpty() {
		return L.next == null;
	}

	// 入栈
	public void push(LinkNode newLinkNode) {
		LinkNode p = L;
		while (p.next != null) {
			p = p.next;
		}
		p.next = newLinkNode;
	}

	// 出栈
	public LinkNode pop() {
		if (isEmpty()) {
			throw new RuntimeException("栈空！");
		}

		LinkNode p = L;
		LinkNode data;
		while (p.next.next != null) {
			p = p.next;
		}
		data = p.next;
		p.next = null;

		return data;
	}

	// 查看，倒序
	public void showStack() {

		if (isEmpty()) {
			System.out.println("栈空！");
			return;
		}
		
		// 两个链表，一个记录新的
		LinkList list = new LinkList();
		// 两个结点，一个记录原始链表，一个新增到链表后，只遍历，不改变
		LinkNode newLinkNode = null;
		
		LinkNode p = L.next;
		
		// 每遍历一个原始链表结点，就加到新链表头上
		while (p != null) {
			//新增一个结点，然后放到新链表后面
			
			newLinkNode = new LinkNode(p.no);
			
			newLinkNode.next = list.L.next;
			list.L.next = newLinkNode;
			p = p.next;
		}
		
		// 遍历新链表
		LinkNode n =  list.L.next;
		while (n != null) {
			System.out.println("-" + n);
			n = n.next;
		}
	}
	
}

class LinkNode {
	public int no;
	public LinkNode next;

	public LinkNode() {
		super();
	}

	public LinkNode(int no) {
		super();
		this.no = no;
	}

	@Override
	public String toString() {
		return "LinkNode [no=" + no + "]";
	}

}